package com.zzyl.intercept;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信小程序端 --- 拦截器
 */

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    /**
     * 拦截器执行方法
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  当前请求所映射的处理器
     * @return         拦截结果
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
            如果不是映射的方法就放行，比如跨域验证请求、静态资源等不需要身份校验的请求（swagger）
            HandlerMethod：【Controller对应的接口方法】
         */
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //1、获取请求头中的 Token【前端为 authorization】
        String token = request.getHeader(Constants.USER_TOKEN);

        //记录日志
        log.info("颁发的Token为：{}",token);

        //2、判断是否得到Token
        if (StrUtil.isBlank(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        //3、校验令牌是否合法【解析】
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);

        //4、令牌不合法抛出异常
        if (ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        Object userId = claims.get(Constants.JWT_USERID);
        if (ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        //5、向下传递【本地线程，用于满足多个需要userId的需求】
        UserThreadLocal.set(Long.parseLong(userId.toString()));

        //6、放行
        return true;
    }


    /**
     * 拦截器执行结束方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放 ThreadLocal 中存储的 userId 数据，避免内存溢出
        UserThreadLocal.remove();
    }



}
